package com.bite.demospringmvc;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.Arrays;

@RequestMapping("/session")
@RestController
public class SessionController {
    @RequestMapping("/getC")
    public String getCookies(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            Arrays.stream(cookies).forEach(ck -> System.out.println(ck.getName() + ":" + ck.getValue()));
        }
        return "获取cookie值成功。";
    }

    @RequestMapping("/getC2")
    public String getCookies2(@CookieValue("nihao") String nihao){

        return "获取cookie值成功。nihao" + nihao;
    }
    @RequestMapping("/setSess")
    public String setSess(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("name", "zhangsan");
        return "设置Session成功";
    }

    @RequestMapping("/getSess")
    public String getSess(HttpServletRequest request){
        HttpSession session = request.getSession();
        String name = (String)session.getAttribute("name");
        return "获取Session: " + name;
    }


    @RequestMapping("/getSess2")
    public String getSess2(@SessionAttribute("name") String name){
        return "获取Session: " + name;
    }

    @RequestMapping("/getSess3")
    public String getSess3(HttpSession session){
        String name = (String)session.getAttribute("name");
        return "获取到Session :" + name;
    }

}
